package com.vshop.controller.other;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.vshop.entity.comentity.UserEmailAndDeviceSubscribeInfo;
import com.vshop.entity.interfacerequest.ExceptionRequest;
import com.vshop.entity.interfacerequest.subscribe.request.RequestSubscribe;
import com.vshop.entity.interfacerequest.subscribe.request.RequestSubscribeData;
import com.vshop.entity.interfacerequest.subscribe.request.RequestSubscribeTradeData;
import com.vshop.entity.interfacerequest.subscribe.response.ResponseSubscribe;
import com.vshop.entity.interfacerequest.subscribe.response.ResponseSubscribeData;
import com.vshop.service.SequenceService;
import com.vshop.service.UserEmailAndDeviceSubscribeService;
import com.vshop.utils.Md5Encrypt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 邮件订阅通知
 *
 * @author lm
 * @date 2019/03/07
 */
@RestController
@Api(description = "邮件订阅通知")
@Slf4j
public class SubscribeInformController {
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    private UserEmailAndDeviceSubscribeService subscribeService;

    @CrossOrigin
    @PostMapping(value = "subscribe", produces = "application/json;charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "邮件订阅通知", response = ResponseSubscribe.class)
    public String subscribe(@ApiParam @RequestBody RequestSubscribe request) {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        //3,定义要回复的内容
        String jsonString;
        ExceptionRequest utils = new ExceptionRequest();
        String requestStr = JSON.toJSONString(request);
        if (requestStr == null) {
            log.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            log.info("【邮件通知】请求：" + requestStr);
            RequestSubscribe requestPackage = JSONArray.parseObject(requestStr, RequestSubscribe.class);
            String requestSign = requestPackage.getSign();
            if (requestPackage.getSign() == null) {
                log.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                RequestSubscribeData requestData = requestPackage.getData();
                if (requestPackage.getData() == null) {
                    log.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String partnerCode = requestData.getPartnerCode();
                    String tradeTime = requestData.getTradeTime();
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();
                    String version = requestData.getVersion();
                    RequestSubscribeTradeData requestTradeData = requestData.getTradeData();

                    if (StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(partnerCode) || StringUtils.isBlank(tradeTime) || StringUtils.isBlank(tradeType) || lang == null || version == null || requestTradeData == null) {
                        log.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {
                        // 将请求体json转成String
                        String str = JSON.toJSONString(requestData);
                        //log.info("签名主体：" + str);
                        // 将Str拿去计算签名
                        String sign = utils.calculateSignature(str);
                        log.info("计算的签名是：" + sign);
                        if (!requestSign.equalsIgnoreCase(sign)) {
                            jsonString = utils.signatureFailure(ConnSeqNo, tradeTime, tradeType, "0001", "签名有误，请确认签名！");
                            return jsonString;
                        } else {//签名验证通过

                            String deviceCode = requestTradeData.getDeviceCode();
                            String payId = requestTradeData.getPayId();
                            String emailCode = requestTradeData.getEmailCode();
                            String troubleText = requestTradeData.getTroubleText();
                            String submitType = requestTradeData.getSubmitType();

                            if (StringUtils.isBlank(deviceCode) || StringUtils.isBlank(payId) || StringUtils.isBlank(emailCode) || null == troubleText || StringUtils.isBlank(submitType)) {
                                log.info("请求报文不合法:tradeData参数不合法");
                                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                                return jsonString;
                            } else {
                                //查找数据库里面有没有设备码对应的email地址
                                if ("1".equals(submitType)) {
                                    //订阅 ：1，订阅一个iccid只允许订阅一次，仅能绑定一个邮箱；已经订阅的用户不允许在前端再显示订阅窗口。
                                    int c = subscribeService.queryEmailCodeBydeviceCode(deviceCode, partnerCode);
                                    if (c <= 0) {
                                        UserEmailAndDeviceSubscribeInfo info = new UserEmailAndDeviceSubscribeInfo();
                                        info.setPartnerCode(partnerCode);
                                        info.setDeviceCode(deviceCode);
                                        info.setEmailCode(emailCode);
                                        info.setPayId(payId);
                                        info.setTroubleText(troubleText);
                                        info.setSubmitType(submitType);
                                        subscribeService.insertSubscribeInfo(info);
                                    }
                                } else {

                                    //异常信息提交：2，异常信息允许同个iccid重复，多次提交；前后端都不做控制。

                                    UserEmailAndDeviceSubscribeInfo info = new UserEmailAndDeviceSubscribeInfo();
                                    info.setSubmitType(submitType);
                                    info.setPartnerCode(partnerCode);
                                    info.setDeviceCode(deviceCode);
                                    info.setEmailCode(emailCode);
                                    info.setPayId(payId);
                                    info.setTroubleText(troubleText);
                                    info.setSubmitType(submitType);
                                    subscribeService.insertSubscribeInfo(info);
                                }

                                //回复接口
                                ResponseSubscribeData data = new ResponseSubscribeData();
                                data.setConnSeqNo(ConnSeqNo);
                                data.setPartnerCode(partnerCode);
                                data.setTradeType(tradeType);
                                data.setTradeTime(tradeTime);
                                data.setTradeRstCode("0000");
                                if (lang.equals("cn") || StringUtils.isNotBlank(lang)) {
                                    data.setTradeRstMessage("成功");
                                } else {
                                    data.setTradeRstMessage("success");
                                }
                                ResponseSubscribe response = new ResponseSubscribe();
                                response.setData(data);
                                response.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));

                                jsonString = JSON.toJSONString(response);
                                log.info("【邮件通知】响应：" + jsonString);
                                return jsonString;

                            }
                        }
                    }
                }
            }
        }

    }


}
